package net.oschina.app.util;

import net.oschina.app.MApp;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by foty on 2017/4/1.
 * 一个连接网络，从服务器获取数据的框架
 */

public class MyHttpUtils<T> {
//http://localhost:8080/oschina/list/news/page0.xml -- 咨询的接口  返回类型： XML

    public void getDate(String url, final Class<T> clazz, final OngetDatesResult result){
        final String key = Md5Utils.md5(url);
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String results = response.body().string();
                //缓存数据
                MApp.mCacheUtils.saveCache(key,results);

                byte[] bytes = results.getBytes();
                T bean = XmlUtils.toBean(clazz,bytes);
 //               InputStream is = response.body().byteStream();
//                T newsList = (T) XmlUtils.toBean(clazz,is);

                result.Onsucessful(bean);

            }
        });
    }

    //
    public interface OngetDatesResult<T>{
        void Onsucessful(T bean);
        void Onfail();
    }

}
